package com.etcn.common.controller;

import java.nio.charset.Charset;
import java.util.HashMap;

import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.etcn.common.Enum.ReturnFlag;
import com.etcn.common.beanvalidator.BeanValidators;
import com.etcn.common.exception.BusinessException;
import com.etcn.common.json.JResult;


/**
 * Controller基础类
 * @author: guozc
 * @date: 2015年4月13日
 */
public class BaseController {
    /**
     * 异常logger
     */
    protected Logger errorLogger = LoggerFactory.getLogger("error_file_log");
    
	// 异常处理
	@ExceptionHandler(Exception.class)
	public ResponseEntity<Object> exceptionHandler(Exception exception) {
		if(!(exception instanceof BusinessException)){
			errorLogger.error("服务器异常", exception);
		}
		String errorMesssage = "服务器异常";
		HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
		// 参数校验错误异常
		if(exception instanceof ConstraintViolationException){
			ConstraintViolationException ex = (ConstraintViolationException) exception;
			errorMesssage = BeanValidators.extractMessageToString(ex);
			httpStatus = HttpStatus.OK;
		}else if(exception instanceof BusinessException){
			BusinessException ex = (BusinessException) exception;
			errorMesssage = ex.getMessage();
			httpStatus = HttpStatus.OK;
		}else if(exception instanceof MissingServletRequestParameterException){
			MissingServletRequestParameterException ex = (MissingServletRequestParameterException)exception;
			errorMesssage = ex.getMessage();
			httpStatus = HttpStatus.OK;
		}else if(exception instanceof ServletRequestBindingException){
			ServletRequestBindingException ex = (ServletRequestBindingException)exception;
			errorMesssage = ex.getMessage();
			httpStatus = HttpStatus.OK;
		}
		HttpHeaders responseHeaders = new HttpHeaders();
		MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
		responseHeaders.setContentType(mediaType);
		JResult jResult = null;
		if(exception.getMessage().indexOf("doesn't exist") != -1){
			httpStatus = HttpStatus.OK;
			jResult = new JResult();
			jResult.setRetCode(ReturnFlag.SUCCESS);
			jResult.setRetMsg("success");
			jResult.setData(new HashMap<String, Object>());
		}else{
			jResult = new JResult();
			jResult.setRetCode(ReturnFlag.FAIL);
			jResult.setRetMsg(errorMesssage);
		}
		ResponseEntity<Object> reponseEntity = new ResponseEntity<Object>(jResult, httpStatus);
		return reponseEntity;
	}
	
}
